<?php
/**
 * MySQL异步查询示例脚本：
 * @filename p_async.php
 * @url http://test.979137.com/ParallelSQL/p_async.php
 */
 
//期望结果集：获取以下用户的每个月每个APP的消费统计
$top = array('979137', '555555', '666666', '888888', '999999');
$ret = array_fill_keys($top, array());
 
//组织结构查询
$cmd = $resources = array();
$sql = "SELECT access_key,SUM(amount) sum_amount FROM consume_2016%s WHERE uid=%d AND product='SAE' GROUP BY access_key"; 
foreach($top as $uid) {
    for($i = 1; $i <= 12; $i++) {
        $ret[$uid][$i] = $tmp = array(); 
            $tmp['uid'] = $uid; 
            $tmp['month'] = $i; 
            $tmp['resource'] = $resources[] = new \mysqli('localhost', 'root', '123456', 'sae', '3306'); 
            $tmp['resource']->set_charset('utf8');
            $tmp['resource']->query(sprintf($sql, sprintf('%02d', $i), $uid), MYSQLI_ASYNC);
        $tag = spl_object_hash($tmp['resource']);
        $cmd[$tag] = $tmp;
    }
}
 
$total = $query_times = count($resources);
 
//获取结果
do {
    $read = $error = $reject = $resources;
    //等待查询结束
    if (!\mysqli::poll($read, $error, $reject, 1)) {
        continue;
    }   
    //批量获取结果
    foreach($read as $resource) {
        $result = $resource->reap_async_query();
        if ($result) {
            $tag = spl_object_hash($resource);
            $uid = $cmd[$tag]['uid'];
            $month = $cmd[$tag]['month'];
            while(($row = $result->fetch_assoc()) != false) {
                $ret[$uid][$month][$row['access_key']] = $row['sum_amount'];
            }   
            $result->free();
            $total--;
     
        } else die('MySQLi error: '.$resource->error);
    }   
} while ($total > 0);
 
var_dump($ret);

?>
